import JDbcutils.JDBCUtil;
import Mobel.Student;
import org.junit.Test;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class TestJdbc2 {
    //1. 获取JDBCTemplate对象
    private JdbcTemplate template = new JdbcTemplate(JDBCUtil.getDatasource());
    /**
     * 1. 添加一条记录
     */
@Test
    public void test1() {
        String sql = "insert into student values(null,?,?,?,?,?)";
        int count = template.update(sql,  "cc", "男",22,"计算机","2024-1-1");
        System.out.println(count);

    }
    public void test3() {
        String sql = "delete from student where id = ?";
        int count = template.update(sql, 9);
        System.out.println(count);
    }
    public void test4() {
        String sql = "select * from student where id = ?";
        Map<String, Object> map = template.queryForMap(sql, 17);
        System.out.println(map);
    }
    public void test6() {
        String sql = "select * from student";
        List<Student> list = template.query(sql, new RowMapper<Student>() {

            @Override
            public Student mapRow(ResultSet rs, int i) throws SQLException {
                Student student = new Student();
                int id = rs.getInt("id");
                String name = rs.getString("name");
                String sex = rs.getString("sex");
                int age = rs.getInt("age");
                String major = rs.getString("major");
                String time = rs.getString("time");
                student.setId(id);
                student.setName(name);
                student.setSex(sex);
                student.setAge(age);
                student.setMajor(major);
                student.setTime(time);
                return student;
            }
        });


        for (Student student : list) {
            System.out.print("id:"+student.getId());
            System.out.print("姓名:"+student.getName());
            System.out.print("性别:"+student.getSex());
            System.out.print("年龄:"+student.getAge());
            System.out.print("专业"+student.getMajor());
            System.out.println("时间:"+student.getTime());
        }
    }
    public void test6_2() {

        String sql = "select * from student";
        List<Student> list = template.query(sql, new BeanPropertyRowMapper<Student>(Student.class));
        for (Student student : list) {
            System.out.println(student);
        }
    }

}
